#include "FileTest.h"
#include <stdio.h>
#include <string.h>

/*
 * Created: 2/27/12; CGP
Do the following 1000 times (needs to be automated!):

a) Create a new file (opened for writing)
b) Write multiple bytes of data into the file
c) Close the file
d) Open the same file for reading
e) Read all the data & verify that the data was the same as expected.
f) Make sure that when you read past the end of the file, you can't read more data. (i.e., End of File is detected correctly).
g) Delete the file
 */

#define NUMBER_ITERATIONS 1000
#define NUMBER_WRITES 1000

// Usage: Part1: No command line arg
///    Part1: with a command line argument
int main(int argc, char *argv[]) {
    int length;
    printf("Starting test...\n"); fflush(stdout);
    FileTest ft;
    const char *fileName1 = "SOURCE";
    unsigned char data[] = "abcdefghijklmnopqrstuvwxyz";
    File *f1;

    printf("Writing to file...\n");
    for (int iteration=0; iteration < NUMBER_ITERATIONS; iteration++) {
        f1 = new File(fileName1, "w");

        for (int i=0; i < NUMBER_WRITES; i++) {
            length = f1->Write(data + (i % 10), 1);
        }
        if (! f1->Close()) {
            printf("ERROR: Could not close file\n");
        }
        delete f1;

        f1 = new File(fileName1, "r");
        unsigned char buffer;
        for (int i=0; i < NUMBER_WRITES; i++) {
            length = f1->Read(&buffer, 1);
            
            if (length != 1) {
                printf("ERROR: Could not read back all bytes of file\n");
            }
            
            if (data[(i % 10)] != buffer) {
                printf("ERROR: Buffer is not equal to data written (expected= %c, actual= %c)\n",
                    data[i], buffer);
            }
        }

        length = f1->Read(&buffer, 1);
        if (length != 0) {
            printf("ERROR: End of file not correctly reached (read returned= %d)\n", length);
        }
        
        if (! f1->Close()) {
            printf("ERROR: Could not close file\n");
        }

        delete f1;

        if (! File::Delete(fileName1)) {
            printf("ERROR: Could not delete file: %s\n", fileName1);
        } else {
            printf("SUCCESS: It seems we were able to delete the file!\n");
        }
    }
}





